package com.treeTest;

import com.google.common.collect.Lists;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {
        List<Menu> menus = Arrays.asList(
                new Menu(1,"根节点",0, 1),
                new Menu(2,"子节点1",1, 2),
                new Menu(3,"子节点1.1",2, 3),
                new Menu(4,"子节点1.2",2, 4),
                new Menu(5,"根节点1.3",2, 5),
                new Menu(6,"根节点2",1, 6),
                new Menu(7,"根节点2.1",6, 7),
                new Menu(8,"根节点2.2",6, 8),
                new Menu(9,"根节点2.2.1",7, 9),
                new Menu(10,"根节点2.2.2",7, 10),
                new Menu(11,"根节点3",1, 11),
                new Menu(12,"根节点3.1",11, 12)
        );

        //获取父节点
        List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
                (m) -> {
                    m.setChildList(getChildrens(m, menus));
                    return m;
                }
        ).sorted(Comparator.comparing(Menu::getOrder)).collect(Collectors.toList());

        System.out.println("-------转json输出结果-------");
    }

    private static List<Menu> getChildrens(Menu root, List<Menu> all) {
        List<Menu> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), root.getId());
        }).map(
                (m) -> {
                    m.setChildList(getChildrens(m, all));
                    return m;
                }
        ).sorted(Comparator.comparing(Menu::getOrder)).collect(Collectors.toList());
        return children;
    }
}
